<template>
  <view class="timeline-container">
    <!-- 导航栏 -->
    <nav-bar></nav-bar>
    <!-- 工作时间设置 -->
    <view class="time-section">
      <view class="section-title">工作时间</view>
      <view class="time-picker" @tap="showTimePicker">
        <text>{{ workTime.start }}-{{ workTime.end }}</text>
        <text class="iconfont icon-arrow-right"></text>
      </view>
    </view>

    <!-- 工作日选择 -->
    <view class="weekday-section">
      <view class="weekday-grid">
        <view 
          class="weekday-item" 
          :class="{ 
            active: index === 0 ? (selectedDays.length === 7) : selectedDays.includes(index)
          }"
          v-for="(day, index) in weekdays" 
          :key="index"
          @tap="toggleDay(index)"
        >
          {{ index === 0 ? (selectedDays.length === 7 ? '全不选' : '全选') : day }}
        </view>
      </view>
    </view>

    <!-- 保存按钮 -->
    <view class="save-button" @tap="saveSettings">
      <text>保存</text>
    </view>

    <!-- 时间选择弹窗 -->
    <view class="custom-popup" v-if="showPopup">
      <view class="popup-mask" @tap="cancelSelect"></view>
      <view class="popup-content">
        <view class="time-popup">
          <view class="close-icon" @tap="cancelSelect">×</view>
          <view class="time-selector">
            <!-- 开始时间选择器 -->
            <picker-view
              :value="startTimePickerValue"
              @change="onStartTimeChange"
              class="time-picker-view"
              indicator-style="height: 100rpx;"
              :mask-style="maskStyle"
            >
              <picker-view-column>
                <view class="picker-item" v-for="hour in hours" :key="hour">
                  {{ hour.padStart(2, '0') }}
                </view>
              </picker-view-column>
              <picker-view-column style="width: 50rpx;">
                <view class="picker-separator">:</view>
              </picker-view-column>
              <picker-view-column>
                <view class="picker-item" v-for="minute in halfHourMinutes" :key="minute">
                  {{ minute.padStart(2, '0') }}
                </view>
              </picker-view-column>
            </picker-view>
            
            <!-- 结束时间选择器 -->
            <picker-view
              :value="endTimePickerValue"
              @change="onEndTimeChange"
              class="time-picker-view"
              indicator-style="height: 100rpx;"
              :mask-style="maskStyle"
            >
              <picker-view-column>
                <view class="picker-item" v-for="hour in hours" :key="hour">
                  {{ hour.padStart(2, '0') }}
                </view>
              </picker-view-column>
              <picker-view-column style="width: 50rpx;">
                <view class="picker-separator">:</view>
              </picker-view-column>
              <picker-view-column>
                <view class="picker-item" v-for="minute in halfHourMinutes" :key="minute">
                  {{ minute.padStart(2, '0') }}
                </view>
              </picker-view-column>
            </picker-view>
          </view>
          <view class="confirm-btn" @tap="confirmSelect">
            确定
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import NavBar from '@/components/nav-bar/nav-bar.vue'
export default {
	components: {
		NavBar
	},
  data() {
    return {
      weekdays: ['全选', '周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      selectedDays: [],
      workTime: {
        start: '08:00',
        end: '22:00'
      },
      showPopup: false,
      startTimePickerValue: [8, 0, 0],
      endTimePickerValue: [22, 0, 0],
      hours: Array.from({length: 15}, (_, i) => String(i + 8)), // 从8点到22点
      halfHourMinutes: ['00', '30'], // 只包含整点和半点
      maskStyle: 'background-image: linear-gradient(180deg, rgba(255, 255, 255, 0.95), rgba(255, 255, 255, 0.6)), linear-gradient(0deg, rgba(255, 255, 255, 0.95), rgba(255, 255, 255, 0.6));',
      tempTime: {
        start: '',
        end: ''
      } ,// 临时存储选择的时间
      schedule:null
    }
  },

  onLoad() {
    this.loadSettings()
  },

  methods: {
    goBack() {
      uni.navigateBack()
    },

    toggleDay(index) {
      if (index === 0) {
        // 点击"全不选"
        this.selectedDays = this.selectedDays.length ? [] : [1, 2, 3, 4, 5, 6, 7]
      } else {
        const dayIndex = this.selectedDays.indexOf(index)
        if (dayIndex > -1) {
          this.selectedDays.splice(dayIndex, 1)
        } else {
          this.selectedDays.push(index)
        }
      }
    },

    showTimePicker() {
      console.log('showTimePicker')
      // 初始化临时时间为当前工作时间
      this.tempTime = {
        start: this.workTime.start,
        end: this.workTime.end
      }
      
      // 确保值被正确初始化
      const [startHour, startMinute] = this.workTime.start.split(':').map(Number)
      const [endHour, endMinute] = this.workTime.end.split(':').map(Number)
      
      // 调整分钟到最接近的半小时值(0或30)
      const startMinuteIndex = startMinute < 15 ? 0 : (startMinute < 45 ? 1 : 0)
      const endMinuteIndex = endMinute < 15 ? 0 : (endMinute < 45 ? 1 : 0)
      
      // 调整小时索引，因为hours数组从8开始
      this.startTimePickerValue = [
        Math.max(0, Math.min(this.hours.length - 1, startHour - 8)),
        0,
        startMinuteIndex
      ]
      
      this.endTimePickerValue = [
        Math.max(0, Math.min(this.hours.length - 1, endHour - 8)),
        0,
        endMinuteIndex
      ]
      
      // 设置弹窗显示状态
      this.showPopup = true
    },

    onTimeChange(e) {
      const values = e.detail.value
      const startHour = values[0]
      const endHour = values[2]
      
      this.tempTime = {
        start: `${String(startHour).padStart(2, '0')}:00`,
        end: `${String(endHour).padStart(2, '0')}:00`
      }
    },

    onStartTimeChange(e) {
      const values = e.detail.value
      const hourIndex = values[0]
      const minuteIndex = values[2]
      
      // 小时值需要加上8，因为我们的hours数组是从8开始的
      const hour = this.hours[hourIndex]
      const minute = this.halfHourMinutes[minuteIndex]
      
      this.tempTime.start = `${hour.padStart(2, '0')}:${minute}`
    },
    
    onEndTimeChange(e) {
      const values = e.detail.value
      const hourIndex = values[0]
      const minuteIndex = values[2]
      
      // 小时值需要加上8，因为我们的hours数组是从8开始的
      const hour = this.hours[hourIndex]
      const minute = this.halfHourMinutes[minuteIndex]
      
      this.tempTime.end = `${hour.padStart(2, '0')}:${minute}`
    },

    cancelSelect() {
      this.showPopup = false
    },

    confirmSelect() {
      if (this.tempTime.start && this.tempTime.end) {
        this.workTime = {...this.tempTime}
      }
      this.showPopup = false
    },

    async loadSettings() {
      try {
        // 从本地存储获取techId
        const userInfo = uni.getStorageSync('userInfo')
        if (!userInfo || !userInfo.techId) {
          throw new Error('未找到技师ID')
        }

        const result = await uni.request({
          url: `${uni.$config.baseUrl}/schedule/schedule/listAll`,
          method: 'GET',
          data: {
            technicianId: userInfo.techId
          }
        })

        if (result.data.code === 200 && result.data.rows && result.data.rows.length > 0) {
          const schedule = result.data.rows[0] // 获取第一条记录
          this.schedule = schedule
          
          // 确保开始时间不早于8:00
          let startHour = 8
          let startMinute = 0
          if (schedule.startTime) {
            const [hour, minute] = schedule.startTime.split(':').map(Number)
            if (hour >= 8 && hour <= 22) {
              startHour = hour
              startMinute = minute
            }
          }
          
          // 确保结束时间不晚于22:00
          let endHour = 22
          let endMinute = 0
          if (schedule.endTime) {
            const [hour, minute] = schedule.endTime.split(':').map(Number)
            if (hour >= 8 && hour <= 22) {
              endHour = hour
              endMinute = minute
            }
          }
          
          // 设置工作时间
          this.workTime = {
            start: `${String(startHour).padStart(2, '0')}:${String(startMinute).padStart(2, '0')}`,
            end: `${String(endHour).padStart(2, '0')}:${String(endMinute).padStart(2, '0')}`
          }
          
          // 将workDays字符串转换为数组
          this.selectedDays = schedule.workDays ? schedule.workDays.split(',').map(Number) : []
          
          // 调整分钟到最接近的半小时值(0或30)
          const startMinuteIndex = startMinute < 15 ? 0 : (startMinute < 45 ? 1 : 0)
          const endMinuteIndex = endMinute < 15 ? 0 : (endMinute < 45 ? 1 : 0)
          
          // 调整小时索引，因为hours数组从8开始
          this.startTimePickerValue = [
            Math.max(0, Math.min(this.hours.length - 1, startHour - 8)),
            0,
            startMinuteIndex
          ]
          
          this.endTimePickerValue = [
            Math.max(0, Math.min(this.hours.length - 1, endHour - 8)),
            0,
            endMinuteIndex
          ]
          
          // 初始化临时时间
          this.tempTime = {
            start: this.workTime.start,
            end: this.workTime.end
          }
        }
      } catch (err) {
        console.error('加载工作时间设置失败:', err)
        uni.showToast({
          title: err.message || '加载失败',
          icon: 'none'
        })
      }
    },

    async saveSettings() {
      try {
        // 从本地存储获取techId
        const userInfo = uni.getStorageSync('userInfo')
        if (!userInfo || !userInfo.techId) {
          throw new Error('未找到技师ID')
        }

        // 准备更新数据
        const updateData = {
          ...this.schedule, // 保留原有数据
          technicianId: userInfo.techId,
          startTime: this.workTime.start,
          endTime: this.workTime.end,
          workDays: this.selectedDays.join(',') // 将数组转换为逗号分隔的字符串
        }

        const result = await uni.request({
          url: `${uni.$config.baseUrl}/schedule/schedule`,
          method: 'PUT',
          data: updateData
        })

        if (result.data.code === 200) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
          // setTimeout(() => {
          //   uni.navigateBack()
          // }, 1500)
        } else {
          throw new Error(result.data.msg || '保存失败')
        }
      } catch (err) {
        console.error('保存工作时间设置失败:', err)
        uni.showToast({
          title: err.message || '保存失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.timeline-container {
  min-height: 100vh;
  background: #F8F8F8;
  padding-bottom: 120rpx;

  .custom-nav-bar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 88rpx;
    background: #FFFFFF;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    z-index: 100;
    border-bottom: 1rpx solid #F5F5F5;
    
    .left {
      width: 88rpx;
      display: flex;
      align-items: center;
      
      .iconfont {
        font-size: 36rpx;
        color: #333333;
      }
    }
    
    .center {
      flex: 1;
      text-align: center;
      font-size: 32rpx;
      color: #333333;
      font-weight: 500;
    }
  }

  .time-section {
    margin-top: 20rpx;
    background: #FFFFFF;
    padding: 30rpx;

    .section-title {
      font-size: 32rpx;
      color: #333333;
      margin-bottom: 20rpx;
    }

    .time-picker {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 88rpx;
      padding: 0 20rpx;
      background: #F8F8F8;
      border-radius: 8rpx;

      text {
        font-size: 28rpx;
        color: #333333;

        &.iconfont {
          color: #999999;
          font-size: 24rpx;
        }
      }
    }
  }

  .weekday-section {
    margin-top: 20rpx;
    background: #FFFFFF;
    padding: 30rpx;

    .weekday-grid {
      display: flex;
      flex-wrap: wrap;
      gap: 20rpx;

      .weekday-item {
        width: calc((100% - 60rpx) / 4);
        height: 80rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #F8F8F8;
        border-radius: 8rpx;
        font-size: 28rpx;
        color: #666666;

        &.active {
          background: #2B85E4;
          color: #FFFFFF;
        }
      }
    }
  }

  .save-button {
    position: fixed;
    bottom: 40rpx;
    left: 30rpx;
    right: 30rpx;
    height: 88rpx;
    background: #2B85E4;
    border-radius: 44rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    text {
      font-size: 32rpx;
      color: #FFFFFF;
    }
  }

  .custom-popup {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 999;
    
    .popup-mask {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      background-color: rgba(0, 0, 0, 0.4);
    }
    
    .popup-content {
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      transform: translate3d(0, 0, 0);
      transition: all 0.3s;
    }
  }

  .time-popup {
    background: #FFFFFF;
    border-radius: 24rpx 24rpx 0 0;
    overflow: hidden;
    position: relative;
    padding: 60rpx 30rpx 40rpx;

    .close-icon {
      position: absolute;
      right: 30rpx;
      top: 30rpx;
      font-size: 48rpx;
      color: #999;
      z-index: 10;
    }
    
    .time-selector {
      display: flex;
      justify-content: space-around;
      padding: 20rpx 0;
    }

    .time-picker-view {
      width: 220rpx;
      height: 300rpx;
      text-align: center;

      .picker-item {
        line-height: 100rpx;
        text-align: center;
        font-size: 60rpx;
        color: #333;
      }
      
      .picker-separator {
        line-height: 100rpx;
        text-align: center;
        font-size: 60rpx;
        color: #2B85E4;
      }
    }
    
    .confirm-btn {
      margin: 40rpx auto 0;
      height: 88rpx;
      line-height: 88rpx;
      background: #2B85E4;
      color: #FFFFFF;
      font-size: 32rpx;
      text-align: center;
      border-radius: 44rpx;
    }
  }
}
</style> 